import { Action, BelongsTo, Column, Habtm, HasMany, HasOne, Property } from "../types"
// import { mergeActionElements } from "./ActionUtil"
import Validator from 'async-validator'
import { getValidates } from "./ColumnUtil"
import { getInferSelfColumn, getInferTargetColumn, getInferThroughSelfColumn, getRefColumn } from "./SeedUtil"

export function getColumnAndValidator(action: Action, property: Property): [column: Column, validator: Validator] {
  const type = property.type
  const value = property.value
  if(type == 'column') {
    // const column = mergeActionElements(action.columns, value as Column)
    const column = value as Column
    const validator = new Validator({value: getValidates(column)})
    return [column, validator]
  }
  
  if(type == 'belongsTo') {
    const belongsTo = value as BelongsTo
    // const column = mergeActionElements(action.columns, belongsTo.selfSeed.columns[getInferSelfColumn(belongsTo, 'belongsTo')])
    const column = belongsTo.selfSeed.columns[getInferSelfColumn(belongsTo, 'belongsTo')] 
    const validator = new Validator({value: getValidates(column)})
    if(!column.rel) column.rel = `${belongsTo.targetSeed.name}.lookup.${getInferTargetColumn(belongsTo, 'belongsTo')}`
    return [column, validator]
  }
  
  if(type == 'hasOne') {
    const hasOne = value as HasOne
    // const column = mergeActionElements(action.columns, hasOne.selfSeed.columns[hasOne.selfColumn])
    const column = hasOne.selfSeed.columns[hasOne.selfColumn]
    const validator = new Validator({value: getValidates(column)})
    if(!column.rel) column.rel = `${hasOne.targetSeed.name}.lookup.${hasOne.targetColumn}`
    return [column, validator]
  }
  
  if(type == 'hasMany') {
    const hasMany = value as HasMany
    // const column = mergeActionElements(action.columns, hasMany.selfSeed.columns[hasMany.selfColumn])
    const column = hasMany.selfSeed.columns[hasMany.selfColumn]
    const validator = new Validator({value: []})
    if(!column.rel) column.rel = `${hasMany.targetSeed.name}.lookup.${hasMany.targetColumn}`
    return [column, validator]
  }

  if(type == 'habtm') {
    const habtm = value as Habtm
    const refColumn = getRefColumn(habtm.throughSeed, getInferThroughSelfColumn(habtm))
    
    // TODO
    const column = { ...refColumn }
    const validator = new Validator({value: []})
    if(!column.rel) column.rel = `${habtm.targetSeed.name}.lookup.${getInferTargetColumn(habtm, 'habtm')}`

    return [column, validator]
  }

  throw Error('不支持的属性类型')
}
